// pages/components/tabbar/tabbar.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const app = getApp()
Component({
  properties: {
    list: {
      type: String,
      value: '',
      observer: function (newData, oldData) {
        this.getNext30Days()
        // this.getLocation()
      }
    },
    getAddrea: {
      type: String,
      value: '',
      observer: function (newData, oldData) {
        if (newData == '1') {
          this.getLocation()
        }
      }
    },
    passenger: {
      type: String,
      value: 'owner',
      observer: function (newData, oldData) {
        console.log(newData, oldData);
        this.setData({
          OwnerOrPassengerRelease: newData || 'owner'
        })
      }
    }
  },
  data: {
    OwnerOrPassengerRelease: wx.getStorageSync('OwnerOrPassengerRelease') || 'owner',
    setOut: {}, // 出发地
    destination: {}, // 目的地
    show: false,
    columns: [
      {
        values: ['今天', '明天', '后天'],
        className: 'column1',
        defaultIndex: 0,
      },
      {
        values: ['0点', '1点', '2点', '3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'],
        className: 'column2',
        defaultIndex: 0,
      },
      {
        values: ['0分', '5分', '10分', '15分', '20分', '25分', '30分', '35分', '40分', '45分', '50分', '55分'],
        className: 'column3',
        defaultIndex: 0,
      }
    ],
    multiArray: [
      ['今天', '明天', '后天'],
      ['0点', '1点', '2点', '3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'],
      ['0分', '5分', '10分', '15分', '20分', '25分', '30分', '35分', '40分', '45分', '50分', '55分']
    ],
    getNext30Days: [],
    multiArrayAll: [],
  },
  methods: {
    // 获取近30天
    getNext30Days() {
      if (this.data.multiArray[0].length > 4) {
        return
      }
      let result = []; // 月日 星期
      let resultAll = []; // 年月日 星期

      for (let i = 0; i < 30; i++) {
        let currentDate = new Date();
        currentDate.setDate(currentDate.getDate() + i);
        let dayOfWeek = currentDate.getDay();
        const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        let datas = new Date(currentDate);
        const Year = datas.getFullYear(); // 年
        const month = datas.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的
        const day = datas.getDate();
        let time = `${month}月${day}日${daysOfWeek[dayOfWeek]}`
        let Ytime = `${Year}年${month > 9?month: '0' + month}月${day > 9? day: '0' + day}日${daysOfWeek[dayOfWeek]}`
        result.push(time);
        resultAll.push(Ytime)
      }
      let columns = this.data.columns
      for (let index = 3; index < result.length; index++) {
        columns[0].values.push(result[index])
      }
      columns[1].values = this.getRemainingHours()
      columns[2].values = this.getRemainingMinutes()

      console.log(columns)

      this.setData({
        getNext30Days: result,
        columns: columns,
        multiArrayAll: resultAll
      })
    },
    // 重新获取近30天
    againgetNext30Days() {
      let result = []; // 月日 星期
      let resultAll = []; // 年月日 星期

      for (let i = 0; i < 30; i++) {
        let currentDate = new Date();
        currentDate.setDate(currentDate.getDate() + i);
        let dayOfWeek = currentDate.getDay();
        const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        let datas = new Date(currentDate);
        const Year = datas.getFullYear(); // 年
        const month = datas.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的
        const day = datas.getDate();
        let time = `${month}月${day}日${daysOfWeek[dayOfWeek]}`
        let Ytime = `${Year}年${month > 9?month: '0' + month}月${day > 9? day: '0' + day}日${daysOfWeek[dayOfWeek]}`
        result.push(time);
        resultAll.push(Ytime)
      }
      let columns = this.data.columns
      for (let index = 3; index < result.length; index++) {
        columns[0].values.push(result[index])
      }
      columns[1].values = this.getRemainingHours()
      columns[2].values = this.getRemainingMinutes()

      console.log(columns)

      this.setData({
        getNext30Days: result,
        columns: columns,
        multiArrayAll: resultAll,
        show: true
      })
    },
    getLocation () {
      let that = this
      util.request('GET', api.getAddres, [app.globalData.position.latitude, app.globalData.position.longitude]).then(function (res) {
        let data = { 
          address: res.province + res.city + res.district + res.recommend,
          latitude: app.globalData.position.latitude,
          longitude: app.globalData.position.longitude,
          name: res.recommend,
          city: res.city
        }
        that.setData({
          setOut: data
        })
        that.triggerEvent('placeOfDeparture', data)
      })
    },
    // 地址选择
    async addressSelection (e) {
      let index = e.currentTarget.dataset.id
      let that = this
      wx.chooseLocation({
        success: function (res) {
          if (index == '0') {
            that.setData({
              setOut: res
            })
          }else {
            that.setData({
              destination: res
            })
          }
        },
        fail(e) {
          console.log(e);
        }
      })
    },
    // 发布行程
    ReleaseSchedule () {
      let setOut = this.data.setOut
      let destination = this.data.destination
      let token = wx.getStorageSync('TwoPlusTravel') || {}
    //   if (Object.keys(token).length == 0) {
    //     wx.showToast({
    //       title: '未登录 请点击下方按钮前往登录',
    //       icon: 'none',
    //       duration: 1500
    //     })
    //     return
    //   }
    if (Object.keys(token).length == 0) {
        wx.showToast({
            title: '未登录 前往登录中~',
            icon: 'none',
            duration: 1500
        })
        let time = setTimeout(() => {
            wx.navigateTo({
            url: '/pages/subpackage/wxlogin/index'
            })
            clearTimeout(time)
        }, 1500)
        return
    }
    // 修改登录end
      if (!setOut.name) {
        wx.showToast({
          title: '请选择出发地',
          icon: 'none'
        })
        return
      }
      if (!destination.name) {
        wx.showToast({
          title: '请选择目的地',
          icon: 'none'
        })
        return
      }
      this.againgetNext30Days()
    },
    onClose () {
      this.setData({
        show: !this.data.show
      })
    },
    // 选择时间中
    onChange (e) {
      let value = e.detail.value
      let index = e.detail.index
      let columns = this.data.columns
      if (index == 0) {
        if (value[0] == '今天') {
          columns[1].values = this.getRemainingHours()
          columns[2].values = this.getRemainingMinutes()
        }else {
          columns[1].values = ['0点', '1点', '2点', '3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点']
          columns[2].values = ['0分', '5分', '10分', '15分', '20分', '25分', '30分', '35分', '40分', '45分', '50分', '55分']
        }
        columns[1].defaultIndex = 0
        columns[2].defaultIndex = 0
      }
      if (index == 1) {
        if (columns[1].values[0] == value[1]) {
          columns[2].values = this.getRemainingMinutes()
        }else {
          columns[2].values = ['0分', '5分', '10分', '15分', '20分', '25分', '30分', '35分', '40分', '45分', '50分', '55分']
        }
        columns[2].defaultIndex = 0
      }
      this.setData({
        columns: columns
      })
    },
    // 选择时间确认
    onConfirm (e) {
      let value = e.detail.value
      console.log(value);
      if (!value[1] || !value[2]) {
        wx.showToast({
          title: '选择的时间有误',
          icon: 'none'
        })
        return
      }
      let hours = value[1].replace('点', '')
      let mm = value[2].replace('分', '')
      let year = this.data.multiArrayAll[e.detail.index[0]]
      let yearindex = year.indexOf('星');
      let yearresult = year.substring(0, yearindex);
      let time = `${value[0]} ${hours}:${Number(mm) > 9?mm: 0+mm}`
      yearresult = yearresult.replace('年', '-').replace('月', '-').replace('日', '')
      let realTime = `${yearresult} ${Number(hours) > 9?hours: 0+hours}:${Number(mm) > 9?mm: 0+mm}`
      let setOut = this.data.setOut
      let destination = this.data.destination
      let data = {
        setOut,
        destination,
        time,
        realTime: realTime
      }
      this.setData({
        show: false
      })
    //   debugger
      if (this.data.OwnerOrPassengerRelease == 'owner') {
        wx.navigateTo({
          url: '/pages/subpackage/TheTripInitiated/index?role=1&data='+JSON.stringify(data),
        })
      }else {
        wx.navigateTo({
          url: '/pages/subpackage/PassengerRelease/index?data='+JSON.stringify(data),
        })
      }
      // this.triggerEvent('ReleaseSchedule', {setOut, destination})
      // wx.navigateTo({
      //   url: '/pages/subpackage/TheTripInitiated/index?data='+JSON.stringify(data),
      // })
    },
    getRemainingHours() {
      let result = [];
      let now = new Date();
      let currentHour = now.getHours();
      for (let i = currentHour; i < 24; i++) {
        result.push(`${i}点`);
      }
      return result;
    },
    getRemainingMinutes() {
      let result = [];
      let now = new Date();
      let currentMinute = now.getMinutes();
      let num = Math.ceil(currentMinute / 5) * 5
      for (let i = num; i < 60; i += 15) {
        result.push(`${i}分`);
      }
      return result;
    },
    ReleaseSwitch (e) {
      console.log(e);
      let nav = e.currentTarget.dataset.index
      this.setData({
        OwnerOrPassengerRelease: nav
      })
      this.triggerEvent('SwitchIdentity', nav)
    }
  }
})